<template>
  <view class="wifi">
    <!-- 波纹圈 -->
    <view class="ripple">
      <view class="avatar">
        <image class="image" src="../../../static/image/Bluetooth/Bluetooth-wirte.png"></image>
      </view>
      <view class="inner"></view>
      <view class="inner outter"></view>
    </view>
    <view class="input-group">
      <u-form ref="uForm" :model="picker.form">
        <u-form-item label="WIFI">
          <view style="display: flex;width: 100%;align-items: center;">
            <u-input v-model="picker.form.ssid" :select-open="picker.show" style="margin-right: 10px;flex: 1;"/>
            <u-button :loading="loading" size="mini" type="primary" @click="setWifiConfig">{{ $t('选取') }}</u-button>
          </view>
        </u-form-item>
        <u-form-item :label="$t('密码')">
          <u-input v-model="picker.form.password" type="password"/>
        </u-form-item>
      </u-form>

      <button class="primary" type="primary" @tap="setWifiInfo">{{ $t('确定') }}</button>
    </view>
    <!-- 选择wifi -->
    <u-picker
        v-model="picker.show"
        :default-selector="[0]"
        :range="picker.data"
        :title="$t('选择wifi')"
        mode="selector"
        range-key="ssid"
        safe-area-inset-bottom
        @confirm="pickerConfirm"
    />

  </view>

</template>

<script>
import {
  mapGetters,
  mapMutations
} from 'vuex'
import mpvuePicker from '@/components/mpvue-picker/mpvuePicker.vue';

export default {
  components: {
    mpvuePicker
  },
  computed: mapGetters(["userInfo", 'api', 'Bluetooth']),
  data() {
    return {
      showPassword: true,
      picker: { //选择wifi
        show: false,
        form: { //已选择的值
          password: '',
          ssid: ''
        },
        data: [],
      },
      loading: false,
      num: 0,//请求次数
    };
  },
  onLoad(e) {
    uni.setNavigationBarTitle({title: this.$t('配置网络')})

    //停止搜索蓝牙
    this.$lizhao.bluetooth.stopBluetoothDevicesDiscovery()
    //获取wifi列表
    this.setWifiConfig()
    //监听回复
    uni.$off('onBLECharacteristicValueChange')
    uni.$on('onBLECharacteristicValueChange', (res) => {
      //console.log(res)
      if (res.cmd === 1) { //获取wifi列表
        res.data = res.data.map(item => {
          item.ssid = item.ssid.replace(/[\\]/g, '');
          return item
        })
        //console.log(res.data);
        this.picker.data = res.data
        if (this.picker.data.length > 0) {
          this.$nextTick(() => {
            this.picker.show = true;
          })
        }
        this.loading = false
      } else if (res.cmd === 2) { //设置wifi
        //获取wifi连接状态
        this.GetWiFiStatus()
      } else if (res.cmd === 10) {
        if (res.data.result === 'success') {
          this.num = 0
          uni.hideLoading()
          setTimeout(() => {
            uni.showToast({
              title: this.$t('设置成功')
            });
          }, 500)
          //处理完之后需要做什么
          if (this.Bluetooth.device.afterTo === '绑定组织') {
            uni.redirectTo({url: '../deviceBind/deviceBind'});
          } else {
            uni.closeBluetoothAdapter();
            uni.navigateBack({
              delta: 1
            });
          }
        } else if (res.data.result === 'connecting') {
          this.num++
          if (this.num > 4) {
            uni.hideLoading()
            uni.showToast({
              title: this.$t('wifi配置失败，请检查密码是否正确'),
              icon: "none"
            });
            this.num = 0
            return
          }
          //获取wifi连接状态
          setTimeout(() => {
            this.GetWiFiStatus()
          }, 2500)
        } else if (res.data.result === 'fail') {
          this.num = 0
          uni.hideLoading()
          uni.showToast({
            title: this.$t('wifi配置失败，请检查密码是否正确'),
            icon: "none"
          });
        }
      }
    })
  },
  onBackPress(options) {
    uni.closeBluetoothAdapter();
    if (options.from === 'navigateBack') {
      return false;
    }
    uni.hideLoading()
    uni.navigateBack({
      delta: 1
    });
    return true;
  },
  methods: {
    //获取wifi状态
    GetWiFiStatus() {
      let body = {}
      let cmd = '000A'//10转成两位的16进制为00 0A
      let len = '00000002'//body的长度为2转成4位的16进制为00 00 00 02
      //获取输入框的十进制数据转换为16进制
      let body_16 = this.$lizhao.scale.strToHexCharCode(JSON.stringify(body))
      let hex = this.Bluetooth.agreement.magic + cmd + this.Bluetooth.agreement.id + len + body_16
      //console.log('最终的16进制的指令',hex);
      //写入指令
      this.$lizhao.bluetooth.writeBLECharacteristicValue(hex)
    },
    pickerConfirm(e) {
      //console.log(e);
      this.picker.form = this.picker.data[e]
    },
    //获取wifi列表
    setWifiConfig() {
      this.loading = true
      let body = {}
      let cmd = '0001' //1转成两位的16进制为00 01
      let len = '00000002' //body的长度为2转成4位的16进制为00 00 00 02
      //获取输入框的十进制数据转换为16进制
      let body_16 = this.$lizhao.scale.strToHexCharCode(JSON.stringify(body))
      let hex = this.Bluetooth.agreement.magic + cmd + this.Bluetooth.agreement.id + len + body_16
      //console.log('最终的16进制的指令', hex);
      //写入指令
      this.$lizhao.bluetooth.writeBLECharacteristicValue(hex)
    },
    //设置wifi
    setWifiInfo() {
      if (!this.picker.form.ssid) {
        uni.showToast({
          title: this.$t('请先选择wifi'),
          icon: "none"
        });
        return
      }
      uni.showLoading({
        title: this.$t('wifi网络配置中') + '...',
        mask: false
      });
      //此时需要注意 wifi名为中文需要把中文的utf-16转成utf-8
      let body = {
        "ssid": this.$lizhao.scale.utf16to8(this.picker.form.ssid),
        "password": this.picker.form.password || ""
      }
      let length = this.$lizhao.scale.switch_sl(JSON.stringify(body).length, 16) // 十进制转十六进制
      let stri = '0'
      for (let i = 0; i < (7 - length.length); i++) {
        stri += '0'
      }
      let cmd = '0002' //2转成两位的16进制为00 02
      let len = stri + length //body的长度为39转成4位的16进制为00 00 00 26
      //十进制数据转换为16进制
      let body_16 = this.$lizhao.scale.strToHexCharCode(JSON.stringify(body))
      //console.log('设置wifi的',body_16);
      let hex = this.Bluetooth.agreement.magic + cmd + this.Bluetooth.agreement.id + len + body_16
      let arr = this.splitArr(hex)
      //多个指令串行发送，并行可能会失败
      this.writeCmd(arr, 0, '设置wifi')
    },
    //arr为hex分割的数组，i为当前数组下标
    async writeCmd(arr, i, text) {
      let res = await this.$lizhao.bluetooth.writeBLECharacteristicValue(arr[i])
      if (res === 'writeBLECharacteristicValue:ok') {
        i++
        if (i > arr.length) {
          return
        }
        this.$lizhao.sleep.sleep(50)
        this.writeCmd(arr, i, text)
      } else {
        this.aginSendFn(text)
      }

    },
    //分割指令每20位分割一下，返回数组
    splitArr(hex) {
      let arr = []
      for (let a = 0; a < Math.ceil(hex.length / 20); a++) {
        let str = hex.slice(a * 20, a * 20 + 20)
        arr.push(str)
      }
      return arr
    },
    //重发机制
    aginSendFn(text) {
      uni.showModal({
        title: this.$t('提示'),
        content: this.$t('系统繁忙'),
        cancelText: this.$t('取消'),
        confirmText: this.$t('重新发送'),
        success: ms => {
          if (ms.confirm) {
            uni.showLoading({
              title: this.$t('重新发送') + '..',
              mask: false
            });
            if (text === '设置wifi') {
              this.setWifiInfo()
            }
          }
          if (ms.cancel) {
            uni.navigateBack({
              delta: 1
            });
          }
        }
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.wifi {
  width: 100%;

  // 波纹圈
  .ripple {
    position: relative;
    width: 100%;
    height: 400rpx;

    .inner {
      width: 150rpx;
      height: 150rpx;
      background: #00aaff;
      border-radius: 50%;
      position: absolute;
      left: 0;
      right: 0;
      margin: auto;
      margin-top: 200rpx;
      z-index: 10;
      animation-duration: 1.5s;
      -webkit-animation-name: state1;
      animation-name: state1;
      -webkit-animation-timing-function: linear;
      animation-timing-function: linear;
      -webkit-animation-iteration-count: infinite;
      animation-iteration-count: infinite;
      opacity: 0;
    }

    @keyframes state1 {
      0% {
        opacity: .5;
        -webkit-transform: scale(1);
        transform: scale(1);
      }

      100% {
        opacity: 0;
        -webkit-transform: scale(2.5);
        transform: scale(2.5);
      }
    }

    .avatar {
      position: absolute;
      left: 0;
      right: 0;
      margin: auto;
      border-radius: 100%;
      margin-top: 200rpx;
      width: 150rpx;
      height: 150rpx;
      background-color: #00aaff;
      z-index: 11;
      display: flex;
      justify-content: center;
      align-items: center;

      .image {
        width: 100rpx;
        height: 100rpx;
        margin: auto;
      }
    }

    .outter {
      animation-delay: 0.3s;
    }
  }

  .input-group {
    padding: 20rpx 40rpx;

    .primary {
      margin-top: 40rpx;
    }
  }
}
</style>
